package com.nidu.demo.web.config;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import com.nidu.demo.common.constants.Constants;
import com.nidu.demo.web.converter.LocalDateConverter;
import com.nidu.demo.web.converter.LocalDateTimeConverter;
import com.nidu.demo.web.filter.ApiAccessLogInterceptor;
import com.nidu.demo.web.util.WebUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Slf4j
@Configuration
@EnableConfigurationProperties(WebProperties.class)  // 添加这个注解
@RequiredArgsConstructor
public class WebAutoConfiguration implements WebMvcConfigurer {

    private final WebProperties webProperties;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1、创建 FastJSON2 消息转换器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();

        // 2、配置 FastJSON2 序列化规则
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setWriterFeatures(
                JSONWriter.Feature.WriteMapNullValue,        // 输出空值字段
                JSONWriter.Feature.PrettyFormat,             // 美化 JSON
                JSONWriter.Feature.WriteLongAsString,        // Long 转字符串，防止 JS 丢失精度
                JSONWriter.Feature.WriteBigDecimalAsPlain,   // BigDecimal 输出为字符串
                JSONWriter.Feature.BrowserCompatible         // 兼容前端（Long 转字符串）
        );

        // 2、统一时间格式：yyyy-MM-dd HH:mm:ss
        fastJsonConfig.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        // 设置字符集
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);

        // 3、绑定配置到转换器
        fastJsonConverter.setFastJsonConfig(fastJsonConfig);

        // 4、设置支持的媒体类型
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON);
        fastJsonConverter.setSupportedMediaTypes(mediaTypes);

        // 5、将 FastJSON2 添加到 Spring 消息转换器列表的首位
        converters.add(0, fastJsonConverter);
    }


    // CORS 跨域配置（允许前端访问后端接口）
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .allowedHeaders("*")
                .maxAge(3600);
    }

    @Bean
    public WebUtils webUtils() {
        return new WebUtils(webProperties);
    }


    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        antPathMatcher.setPathSeparator(Constants.SEPARATOR);

        configurer.setPathMatcher(antPathMatcher)
                .addPathPrefix(webProperties.getAppApi().getPrefix(),
                        clazz -> clazz.isAnnotationPresent(RestController.class) &&
                                antPathMatcher.match(webProperties.getAppApi().getController(), clazz.getPackage().getName()))
                .addPathPrefix(webProperties.getAdminApi().getPrefix(),
                        clazz -> clazz.isAnnotationPresent(RestController.class) &&
                                antPathMatcher.match(webProperties.getAdminApi().getController(), clazz.getPackage().getName()));
    }


    // 配置拦截器（用于用户认证、日志）
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ApiAccessLogInterceptor()).addPathPatterns("/");

        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang"); // 设置语言参数名
        registry.addInterceptor(interceptor);

        // 使用spring security拦截器
        // registry.addInterceptor(new AuthInterceptor())
        //         // 设置需要拦截的路径（这里拦截所有的路径）
        //         .addPathPatterns("/**")
        //         // 设置登录放行
        //         .excludePathPatterns("/login", "/register")
        //         // 设置Swagger访问放行
        //         .excludePathPatterns("/api-docs", "/swagger-ui.html/**", "/swagger-ui.html", "/swagger-resources/**", "/swagger-ui.html#/**")
        //         // 如资源文件放行
        //         .excludePathPatterns("/webjars/**", "/doc.html", "classpath:/META-INF/resources/");
    }

    // 配置参数解析（例如日期格式转换）
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new LocalDateConverter());
        registry.addConverter(new LocalDateTimeConverter());
    }
}
